package com.hunantv.mglive.ui.discovery.publisher.pic;

import java.io.UnsupportedEncodingException;
import java.lang.reflect.Field;
import java.net.URLDecoder;
import java.net.URLEncoder;
import java.util.HashMap;
import java.util.Iterator;
import java.util.Map.Entry;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

import android.content.Context;
import android.content.Intent;
import android.graphics.drawable.Drawable;
import android.net.Uri;
import android.text.Editable;
import android.text.Spannable;
import android.text.SpannableStringBuilder;
import android.text.Spanned;
import android.text.TextUtils;
import android.text.method.LinkMovementMethod;
import android.text.style.ImageSpan;
import android.text.style.URLSpan;
import android.util.Log;
import android.view.View;
import android.widget.EditText;
import android.widget.TextView;

import com.hunantv.mglive.R;
import com.hunantv.mglive.common.MaxApplication;
import com.hunantv.mglive.utils.L;

public class TextViewHelper {
	
	public class SpanPos {
		public SpanPos(int start, int end) {
			this.start = start;
			this.end = end;
		}

		public int start;
		public int end;
	}
	
	public static String emoji[] = { "微笑", "撇嘴", "色", "发呆", "得意", "流泪", "害羞", "闭嘴",
			"睡", "大哭", "尴尬", "发怒", "调皮", "呲牙", "惊讶", "难过", "酷", "冷汗", "抓狂",
			"吐", "偷笑", "可爱", "白眼", "傲慢", "饥饿", "困", "惊恐", "流汗", "憨笑", "大兵",
			"奋斗", "咒骂", "疑问", "嘘", "晕", "折磨", "衰", "骷髅", "敲打", "再见", "擦汗",
			"抠鼻", "鼓掌", "糗大了", "坏笑", "左哼哼", "右哼哼", "哈欠", "鄙视", "委屈", "快哭了",
			"阴险", "亲亲", "吓", "可怜", "菜刀", "西瓜", "啤酒", "篮球", "乒乓", "咖啡", "饭",
			"猪头", "玫瑰", "凋谢", "示爱", "爱心", "心碎", "蛋糕", "闪电", "炸弹", "刀", "足球",
			"瓢虫", "便便", "月亮", "太阳", "礼物", "拥抱", "强", "弱", "握手", "胜利", "抱拳",
			"勾引", "拳头", "差劲", "爱你", "NO", "OK", "爱情", "飞吻", "跳跳", "发抖", "怄火",
			"转圈", "磕头", "回头", "跳绳", "挥手" };

	private String emojiRegex = "";
	private Pattern emojiPattern = null;
	private Pattern urlPattern = null;
//	private Pattern atPattern = null;
	private static TextViewHelper sTextViewHelper = null;

	private TextViewHelper() {
		// TODO Auto-generated constructor stub
		emojiRegex = "\\[/(";
		for (int i = 0; i < emoji.length; i++) {
			emojiRegex += emoji[i];
			if (i != emoji.length - 1)
				emojiRegex += "|";
		}
		emojiRegex += ")\\]";
		
		emojiPattern = Pattern.compile(emojiRegex);
		//http://stackoverflow.com/questions/163360/regular-expresion-to-match-urls-in-java
		//http://stackoverflow.com/questions/3809401/what-is-a-good-regular-expression-to-match-a-url
		urlPattern = Pattern.compile("((https|http|ftp|file):\\/\\/)?(www\\.)?[-a-zA-Z0-9@:%._\\+~#=\\u4e00-\\u9fa5]{1,256}\\.[a-z\\u4e00-\\u9fa5]{2,4}\\b([-a-zA-Z0-9@:%_\\+.~#?!&//=]*)");
//		atPattern = Pattern.compile("circle:\\/\\/at\\?userid=[a-zA-Z0-9_-]+&accounttype=[0-9]+&nickname=[-a-zA-Z0-9@:%_\\+.~#?!&//=]+");
	}
	
	private int getResourceId(String faceName) {
		int index = -1;
		for (int i = 0; i < emoji.length; i++) {
			if (emoji[i].equals(faceName)) {
				index = i + 1;// index start from 1;
				break;
			}
		}
		
		if (index == -1)
			return -1;

		String resourceName = "emoji" + index;
		try {
			Field f = (Field) R.drawable.class.getDeclaredField(resourceName);
			int i = f.getInt(R.drawable.class);
			return i;
		} catch (Exception e) {
			e.printStackTrace();
			return -1;
		}
	}
	
	private int getResourceId(int emoticonIndex) {
		
		if(emoticonIndex < 0 || emoticonIndex >= emoji.length){
			 return -1;
		}
		 
		emoticonIndex++;// index start from 1;
		String resourceName = "emoji" + emoticonIndex;

		try {
			Field f = (Field) R.drawable.class.getDeclaredField(resourceName);
			int i = f.getInt(R.drawable.class);
			return i;
		} catch (Exception e) {
			e.printStackTrace();
			return -1;
		}
	}

	public static TextViewHelper getInstance() {
		if (sTextViewHelper == null) {
			sTextViewHelper = new TextViewHelper();
		}
		return sTextViewHelper;
	}

	//过滤出text中的@功能url
	/*private String filterAtFriendUrl(String text,HashMap<SpanPos, String> atSpanMap){
		if(atSpanMap == null || TextUtils.isEmpty(text))
			return null;
		
		Matcher m = atPattern.matcher(text);
		StringBuilder buildText = null;
		int offset = 0;
		while (m.find()) {
			if (buildText == null) {
				buildText = new StringBuilder(text);
			}
			String atFriendUrl = m.group();
			Uri uri = Uri.parse(atFriendUrl);
			if (TextUtils.isEmpty(uri.getQueryParameter("nickname")))
				continue;

			int start = m.start() + offset;
			int end = m.end() + offset;
			String nickName = null;
			
			try{
				nickName = URLDecoder.decode(uri.getQueryParameter("nickname"),"UTF-8");
			}
			catch(UnsupportedEncodingException e){
				return null;
			}
			
			String atFriendName = "@"+nickName;
			buildText.replace(start, end, atFriendName);
			offset += atFriendName.length() - atFriendUrl.length();
			atSpanMap.put(new SpanPos(start, start + atFriendName.length()), atFriendUrl);
		}

		if (buildText != null && atSpanMap != null) {
			return buildText.toString();
		}
		else
			return null;
	}*/
	
	
	public void setText(TextView tv, String text) {
		
		/*HashMap<SpanPos, String> atSpanMap = new HashMap<SpanPos, String>();
		String filterText = filterAtFriendUrl(text,atSpanMap);//filter @ span
		if(filterText != null){
			text = filterText;
		}
		
		Matcher m = atPattern.matcher(text);*/
		SpannableStringBuilder spannable = new SpannableStringBuilder(text);
		Matcher m = emojiPattern.matcher(text);
		
		while (m.find()) {
//			MttLog.d("tv", "start:" + m.start() + "end:" + m.end() + "face:"
//					+ text.substring(m.start(), m.end()) + "group:" + m.group());
			String faceName = m.group();
			faceName = faceName.substring(2, faceName.length() - 1);
			L.d("tv", "face:" + faceName);

			int resourceId = getResourceId(faceName);
			if (resourceId == 0 || resourceId == -1)
				continue;

			Drawable drawable = MaxApplication.getApp().getAppContext()
					.getResources().getDrawable(resourceId);
			drawable.setBounds(0, 0, drawable.getIntrinsicWidth(),
					drawable.getIntrinsicHeight());

			ImageSpan span = new ImageSpan(drawable, ImageSpan.ALIGN_BASELINE);
			spannable.setSpan(span, m.start(), m.end(),
					Spannable.SPAN_EXCLUSIVE_EXCLUSIVE);
		}

		
		m = urlPattern.matcher(text);
		boolean exitUrl = false;
		while (m.find()) {
			spannable.setSpan(new URLSpan(m.group()){
				@Override
				 public void onClick(View widget) {
					
						String url = getURL();
						
						if(!url.startsWith("http://")  &&
						   !url.startsWith("https://") &&
						   !url.startsWith("ftp://")   &&
						   !url.startsWith("file://")){
							
								url = "http://" + url;
						}//remove this will be crash for www.qq.com ... tab switch failed... todo:: maxxiang...
								
				        Uri uri = Uri.parse(url);
				        Context context = widget.getContext();
				        Intent intent = new Intent(Intent.ACTION_VIEW, uri);
				        intent.addCategory(Intent. CATEGORY_BROWSABLE);  
				        intent.addCategory(Intent. CATEGORY_DEFAULT); 
//				        intent.putExtra(Browser.EXTRA_APPLICATION_ID, context.getPackageName());
				        intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);  
				        context.startActivity(intent);
				    }
				
			},  m.start(), m.end(),Spanned.SPAN_EXCLUSIVE_EXCLUSIVE);  
			exitUrl = true;
		}
		
		//add @ span
		/*if (atSpanMap.size() > 0) {
			Iterator<Entry<SpanPos, String>> iter = atSpanMap.entrySet().iterator();
			while (iter.hasNext()) {
				HashMap.Entry<SpanPos, String> entry = (HashMap.Entry<SpanPos, String>) iter.next();
				SpanPos pos = entry.getKey();
				String atFirendUrl = entry.getValue();
				MttLog.d("span", "url:"+atFirendUrl);
				spannable.setSpan(new AtFriendSpan(atFirendUrl), pos.start, pos.end, Spanned.SPAN_EXCLUSIVE_EXCLUSIVE);
				exitUrl = true;
			}
		}*/
		
		if(exitUrl){
			if(tv instanceof LinkTextView){
				tv.setMovementMethod(LinkTextView.LocalLinkMovementMethod.getInstance());
			}
			else{
				tv.setMovementMethod(LinkMovementMethod.getInstance());
			}
		}
		else{
			tv.setMovementMethod(null);
		}
		
		tv.setText(spannable);
	}
	
	
	public void setTextIgnoreUrl(TextView tv, String text) {
		SpannableStringBuilder spannable = new SpannableStringBuilder(text);
		Matcher m = emojiPattern.matcher(text);
		
		while (m.find()) {
			String faceName = m.group();
			faceName = faceName.substring(2, faceName.length() - 1);
			L.d("tv", "face:" + faceName);

			int resourceId = getResourceId(faceName);
			if (resourceId == 0 || resourceId == -1)
				continue;

			Drawable drawable = MaxApplication.getApp().getAppContext()
					.getResources().getDrawable(resourceId);
			drawable.setBounds(0, 0, drawable.getIntrinsicWidth(),
					drawable.getIntrinsicHeight());

			ImageSpan span = new ImageSpan(drawable, ImageSpan.ALIGN_BASELINE);
			spannable.setSpan(span, m.start(), m.end(),
					Spannable.SPAN_EXCLUSIVE_EXCLUSIVE);
		}
		
		tv.setText(spannable);
	}
	
	public boolean insertEmoticon(EditText tv, int emoticonIndex) {

		if (emoticonIndex < 0 || emoticonIndex >= emoji.length || tv == null || tv.getEditableText() == null) {
			return false;
		}

		int resourceId = getResourceId(emoticonIndex);

		if (resourceId == 0 || resourceId == -1)
			return false;

		String emojiText = "[/" + emoji[emoticonIndex] + "]";
		
		L.d("emoji","selecte emoji text: " + emojiText);
		SpannableStringBuilder spannable = new SpannableStringBuilder(emojiText);

		Drawable drawable = MaxApplication.getApp().getAppContext()
				.getResources().getDrawable(resourceId);
		drawable.setBounds(0, 0, drawable.getIntrinsicWidth(),
				drawable.getIntrinsicHeight());

		ImageSpan span = new ImageSpan(drawable, ImageSpan.ALIGN_BASELINE);
		spannable.setSpan(span, 0, emojiText.length(),
				Spannable.SPAN_EXCLUSIVE_EXCLUSIVE);

		
	   //获取光标所在位置  
	   int index = tv.getSelectionStart();  
	   // 获取EditText中原有的文本内容  
	   Editable editable = tv.getEditableText();  
	   // 在光标所在位置插入表情转换成文本  
	   if (index < 0 || index >= editable.length()) {  
	       editable.append(spannable);  
	   } else {  
	       editable.insert(index, spannable);  
	   }  
		
	   return true;
	}
	
	
	public void backSpace(EditText editText){
		
		if(editText == null)
			return;
		
		Editable content = editText.getText();
		int start = editText.getSelectionStart();  
		int end = TextUtils.getOffsetBefore(content, start);
		content.delete(Math.min(start, end),Math.max(start, end));  
		
	}
	
	
//	public boolean AtFriend(EditText tv, UserInfo friendInfo) {
//		if (tv == null || friendInfo == null)
//			return false;
//
//		String atFriendText = '@' + friendInfo.getSNickname() + " ";
//
//		/*SpannableStringBuilder spannable = new SpannableStringBuilder(atFriendText);
//		String urlNickName = null;
//		try{
//			urlNickName = URLEncoder.encode(friendInfo.getSNickname(),"UTF-8");
//		}
//		catch(UnsupportedEncodingException e){
//			return false;
//		}
//
//		String atFirendUrl = "circle://at?userid=" + friendInfo.getSUserId() +"&accounttype=" + friendInfo.getEAccountType() + "&nickname="+urlNickName;
//		spannable.setSpan(new AtFriendSpan(atFirendUrl), 0, atFriendText.length(), Spanned.SPAN_EXCLUSIVE_EXCLUSIVE);*/
//
//		// 获取光标所在位置
//		int index = tv.getSelectionStart();
//		// 获取EditText中原有的文本内容
//		Editable editable = tv.getEditableText();
//
//		String text = tv.getText().toString();
//		if(text != null && text.length() > 0 &&  text.charAt(index-1) == '@'){
//			backSpace(tv);//删除已经存在的@
//		}
//
//		SpannableStringBuilder spannable = new SpannableStringBuilder(atFriendText);
//		String atFirendUrl = "circle://at?userid=";
//		spannable.setSpan(new AtFriendSpan(atFirendUrl), 0, atFriendText.length(), Spanned.SPAN_EXCLUSIVE_EXCLUSIVE);
//
//		if (index < 0 || index >= editable.length()) {
//			editable.append(spannable);
//		} else {
//			editable.insert(index, spannable);
//		}
//
//
//		return true;
//	}
	
//	public String getOriginalText(EditText tv) {
//		if (tv == null)
//			return null;
//
//		Editable editable = tv.getEditableText();
//		if (editable == null || editable.length() <= 0)
//			return "";
//
//		StringBuilder originalTxt = null;
//		AtFriendSpan[] spanArray = tv.getText().getSpans(0, editable.length(), AtFriendSpan.class);
//		int offset = 0;
//		for (AtFriendSpan span : spanArray) {
//			int start = tv.getText().getSpanStart(span);
//			int end = tv.getText().getSpanEnd(span);
//			if (start != -1 && end != -1) {
//
//				if (originalTxt == null) {
//					originalTxt = new StringBuilder(tv.getText().toString());
//				}
//
//				String url = span.getURL() + " ";
//				MttLog.d("span", "start:" + start + "end" + end + "url:" + url);
//				start += offset;
//				end += offset;
//				originalTxt.replace(start, end, url);
//				offset += url.length() - (end - start);
//			}
//		}
//
//		if (originalTxt != null) {
//			return originalTxt.toString();
//		} else {
//			return tv.getText().toString();
//		}
//	}

}
